package com.hfb.mashibing.alip8.juc.c020;


import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch——在门栓前倒数数字，为0为止
 */
public class T06_TestCountDownLatch extends Thread {

    public static void main(String[] args) {
        useJoin();
        usigCountDownLatch();
    }

    private static void useJoin() {
        Thread[] threads = new Thread[100];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                int res = 0;
                for (int j = 0; j < 100_00; j++) res += j;
            });
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (Thread t : threads) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("end join");
    }

    private static void usigCountDownLatch() {
        Thread[] threads = new Thread[100];
        CountDownLatch latch = new CountDownLatch(threads.length);

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(()->{
                int res = 0;
                for (int j = 0; j < 100_00; j++) res += j;
                // 倒数数字-1:100，99，98，97，。。。
                latch.countDown();
            });
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        try {
            // 用门栓插上门
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("end latch");
    }
}
